package im.starchat.chat.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.squareup.picasso.Picasso;
import im.starchat.chat.R;
import im.starchat.chat.XLApplication;
import im.starchat.chat.activity.old.SettingActivity;
import im.starchat.chat.activity.profile.AttentionActivity;
import im.starchat.chat.activity.profile.ContributionActivity;
import im.starchat.chat.activity.profile.FansActivity;
import im.starchat.chat.activity.profile.MyDiamondActivity;
import im.starchat.chat.activity.profile.MyPreviewListActivity;
import im.starchat.chat.activity.profile.WithdrawActivity;
import im.starchat.chat.activity.profile.ZhiboListActivity;
import im.starchat.chat.rest.RestClient;
import im.starchat.chat.rest.model.ContributionBean;
import im.starchat.chat.rest.model.UserBean;
import im.starchat.chat.rest.model.api.ContributionResponse;
import im.starchat.chat.utils.GsonUtil;
import im.starchat.chat.utils.PreferencesStorageUtil;
import im.starchat.chat.utils.UserUtils;
import im.starchat.chat.view.CircularImageButton;

import butterknife.ButterKnife;
import butterknife.InjectView;
import retrofit.Callback;
import retrofit.RetrofitError;
import retrofit.client.Response;

public class MainTabProfileFragment extends Fragment implements OnClickListener {

    private static final int UPDATE_COVER = 1;

    private static final String TAG = "MainTabProfileFragment";


    @InjectView(R.id.earnings_layout)
    LinearLayout mEarningLayout;
    @InjectView(R.id.diamond_layout)
    LinearLayout mDiamondLayout;
    @InjectView(R.id.attention_layout)
    LinearLayout mAttentionLayout;
    @InjectView(R.id.profile_attention_layout)
    RelativeLayout mHeaderAttentionLayout;
    @InjectView(R.id.profile_fans_layout)
    RelativeLayout mFansLayout;
    @InjectView(R.id.profile_zhibo_layout)
    RelativeLayout mZhiboLayout;
    @InjectView(R.id.parade_layout)
    LinearLayout mParadeLayout;

    @InjectView(R.id.profile_user_name)
    TextView mUserName;
    @InjectView(R.id.profile_user_sex)
    TextView mUserSex;
    @InjectView(R.id.profile_user_detail)
    TextView mUserDetail;
    @InjectView(R.id.profile_zhibo_num)
    TextView mZhiboCount;
    @InjectView(R.id.profile_fans_num)
    TextView mFansCount;
    @InjectView(R.id.profile_attention_num)
    TextView mAttentionCount;
    @InjectView(R.id.profile_money_count)
    TextView mPopularityText;
    @InjectView(R.id.profile_diamond_count)
    TextView mDiamondText;
    @InjectView(R.id.setting)
    ImageView mSettingBtn;
    @InjectView(R.id.iv_zoom)
    ImageView mUserHeaderCover;
    @InjectView(R.id.star_ider)
    ImageView mStarFlag;

    @InjectView(R.id.profile_bar_layout)
    LinearLayout mProfileBarLayout;

    //整个贡献榜的效果
    @InjectView(R.id.contribution_layout)
    LinearLayout mContributionLayout;
    //贡献榜列表
    @InjectView(R.id.contribution_user_layout)
    LinearLayout mContributionUserLayout;

//    @InjectView(R.id.tv_register)
//    TextView mContributionTextview;
    @InjectView(R.id.show_more)
    ImageView mShowMore;

    private ContributionResponse mContributionResponse;


    public static MainTabProfileFragment newInstance() {
        return new MainTabProfileFragment();
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_profile, container, false);
        ButterKnife.inject(this, view);

        if(!TextUtils.isEmpty(UserUtils.getUserInstance().getAvatar())){

            Picasso.with(getActivity()).load(UserUtils.getUserInstance().getAvatar())
                    .placeholder(R.drawable.ic_img_profile_bg)
                    .into(mUserHeaderCover);
        }

        mEarningLayout.setOnClickListener(this);
        mDiamondLayout.setOnClickListener(this);
        mAttentionLayout.setOnClickListener(this);
        mHeaderAttentionLayout.setOnClickListener(this);
        mFansLayout.setOnClickListener(this);
        mZhiboLayout.setOnClickListener(this);
        mParadeLayout.setOnClickListener(this);
        mSettingBtn.setOnClickListener(this);
        mShowMore.setOnClickListener(this);
//        mContributionTextview.setOnClickListener(this);

        refreshAccount(PreferencesStorageUtil.getUserBean(getActivity()));
        getUserInfo();
        getContributionList();

        return view;
    }

    private void getUserInfo(){
        XLApplication.getInstance().getRestClient().getUserInfo(PreferencesStorageUtil.getUserId(getActivity()), new Callback<UserBean>() {
            @Override
            public void success(UserBean userBean, Response response) {
                UserUtils.setUserInstance(userBean);
                PreferencesStorageUtil.setUserBean(getActivity(), GsonUtil.toJson(userBean));
                if (userBean.getAccount() != null) {
                    PreferencesStorageUtil.setDiamondCount(getActivity(), userBean.getAccount().getAmount());
                }
                refreshAccount(userBean);
            }

            @Override
            public void failure(RetrofitError error) {

            }
        });
    }

    private void refreshAccount(UserBean userBean){
        if(userBean != null && mUserName != null){
            mUserName.setText(userBean.getNickname());
            mUserSex.setText(userBean.getGender_text());
            if(!TextUtils.isEmpty(userBean.getDescription())){
                mUserDetail.setText(userBean.getDescription());
            }
            mAttentionCount.setText(userBean.getFollowings_count() + "");
            if (userBean.getAccount() != null) {
                mPopularityText.setText(userBean.getAccount().getTotal_popularity() + "");
                mDiamondText.setText(userBean.getAccount().getAmount() + "");
            }
            mZhiboCount.setText(userBean.getRooms_count() + "");
            mFansCount.setText(userBean.getFollowers_count() + "");

            if(!TextUtils.isEmpty(UserUtils.getUserInstance().getAvatar())){

                Picasso.with(getActivity()).load(UserUtils.getUserInstance().getAvatar())
                        .placeholder(R.drawable.ic_img_profile_bg)
                        .into(mUserHeaderCover);
            }

        }
        refreshStarLayout();

    }

    private void refreshStarLayout(){

        if(PreferencesStorageUtil.isStar(getActivity())){
            mStarFlag.setVisibility(View.VISIBLE);
            mEarningLayout.setVisibility(View.VISIBLE);
            mContributionLayout.setVisibility(View.VISIBLE);
            if(mProfileBarLayout != null)
                mProfileBarLayout.setVisibility(View.VISIBLE);
        }else{
            mStarFlag.setVisibility(View.GONE);
            mEarningLayout.setVisibility(View.GONE);
            mContributionLayout.setVisibility(View.GONE);
            if(mProfileBarLayout != null)
                mProfileBarLayout.setVisibility(View.GONE);
        }

    }

//    private boolean isStart = false;
    @Override
    public void onHiddenChanged(boolean hidden) {
        if(!hidden && mStarFlag != null){
            refreshAccount(UserUtils.getUserInstance());
            getUserInfo();
            getContributionList();
        }
//        isStart = true;
        super.onHiddenChanged(hidden);
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.earnings_layout:
                Intent earningLayout = new Intent();
                earningLayout.setClass(getActivity(), WithdrawActivity.class);
                startActivity(earningLayout);
                break;
            case R.id.diamond_layout:
                Intent myDiamondLayout = new Intent();
                myDiamondLayout.setClass(getActivity(), MyDiamondActivity.class);
                startActivity(myDiamondLayout);
                break;
            case R.id.attention_layout:
            case R.id.profile_attention_layout:
                Intent attentionLayout = new Intent();
                attentionLayout.setClass(getActivity(), AttentionActivity.class);
                startActivity(attentionLayout);
                break;
            case R.id.profile_fans_layout:
                Intent fansLayout = new Intent();
                fansLayout.setClass(getActivity(), FansActivity.class);
                startActivity(fansLayout);
                break;
            case R.id.profile_zhibo_layout:
                Intent zhiboLayout = new Intent();
                zhiboLayout.setClass(getActivity(), ZhiboListActivity.class);
                startActivity(zhiboLayout);
                break;
            case R.id.parade_layout:
                Intent paradeLayout = new Intent();
                paradeLayout.setClass(getActivity(), MyPreviewListActivity.class);
                startActivity(paradeLayout);
                break;
            case R.id.setting:
                Intent toSettingActivityIntent = new Intent(getActivity(), SettingActivity.class);
                startActivity(toSettingActivityIntent);
//                Intent toSettingActivityIntent = new Intent(getActivity(), PlayBackActivity.class);
//                startActivity(toSettingActivityIntent);
                break;
//            case R.id.tv_register:
//                Intent contributionIntent = new Intent(getActivity(), ContributionActivity.class);
//                contributionIntent.putExtra(ContributionActivity.FLAG_USER_ID, PreferencesStorageUtil.getUserId(getActivity()));
//                startActivity(contributionIntent);
//                break;
            case R.id.show_more:
                Intent showMoreIntent = new Intent(getActivity(), ContributionActivity.class);
                showMoreIntent.putExtra(ContributionActivity.FLAG_USER_ID, PreferencesStorageUtil.getUserId(getActivity()));
                startActivity(showMoreIntent);
                break;

        }
    }


//    //向用户服务器获取成员信息
//    private void getMemberInfo() {
//
//
//        //TODO 暂时使用测试房间 11
//        XLApplication.getInstance().getRestClient().getRoomUsers(roomNum + "", "online", new Callback<UserBean[]>() {
//            @Override
//            public void success(UserBean[] userBeans, Response response) {
//                mMemberList.clear();
//                if (userBeans != null) {
//                    for (UserBean userBean : userBeans) {
//                        MemberInfo member = new MemberInfo(userBean.getId() + "", userBean.getNickname(), userBean.getAvatar());
//                        mMemberList.add(member);
//                    }
//                    mNormalMemberList = copyToNormalMember();
//                    mHandler.sendEmptyMessage(UPDAT_MEMBER);
//                }
//            }
//
//            @Override
//            public void failure(RetrofitError error) {
//
//            }
//        });
//    }


    private void getContributionList(){
            XLApplication.getInstance().getRestClient().getContributions(PreferencesStorageUtil.getUserId(getActivity()), 0, RestClient.DEFAULT_PREPAGE, new Callback<ContributionBean[]>() {
                @Override
                public void success(ContributionBean[] userBean, Response response) {

                    int screenDp = (int)(XLApplication.sScreenWidth / XLApplication.sDensity);
                    int maxNum = (screenDp / (44)) - 1;

                    if(userBean != null){
                        if(userBean.length > 0){
                            mContributionUserLayout.removeAllViews();
                            for(int num = 0 ; num < userBean.length && num < maxNum  ; num ++){
                                View view = LayoutInflater.from(getActivity()).inflate(R.layout.view_contribution_user_layout, null , false);
                                CircularImageButton avator = (CircularImageButton) view.findViewById(R.id.avator);
                                if (!TextUtils.isEmpty(userBean[num].getUser().getAvatar())) {
                                    Picasso.with(getActivity()).load(userBean[num].getUser().getAvatar())
                                            .placeholder(R.drawable.channel_head01)
                                            .into(avator);
                                }
                                TextView contributionNum = (TextView) view.findViewById(R.id.contribution_num);
                                if(num < 3){
                                    contributionNum.setVisibility(View.VISIBLE);
                                    contributionNum.setText((num + 1 )+ "");
                                    if(num == 0){
                                        contributionNum.setBackgroundResource(R.drawable.bg_rounded_contribution_list1_bg);
                                    }else if(num == 1){
                                        contributionNum.setBackgroundResource(R.drawable.bg_rounded_contribution_list2_bg);
                                    }else if(num == 2){
                                        contributionNum.setBackgroundResource(R.drawable.bg_rounded_contribution_list3_bg);
                                    }
                                }else{
                                    contributionNum.setVisibility(View.GONE);
                                }
                                mContributionUserLayout.addView(view);
                            }
                        }
                    }
                }

                @Override
                public void failure(RetrofitError error) {
                }
            });
        }


}
